package com.ruoyi.cms.listener;

import com.ruoyi.cms.post.service.ICmsPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import static com.ruoyi.common.constant.RedisConstants.POST_ID_KEY;
import static com.ruoyi.common.constant.RedisConstants.PREFIX;

/**
 *  自定义redis key过期监听器
 * 当我们设置的页面访问量的键过期后, 需要将过期的键的值同步到数据库
 *  以实现一定时间,对数据的持久化(除此之外还设置了定时任务,在每天的2:00同步到数据库 详情: MySchedule.class)
 */
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

  @Autowired
  private StringRedisTemplate stringRedisTemplate;

  @Autowired
  private ICmsPostService postService;

  public KeyExpiredListener(RedisMessageListenerContainer  listenerContainer) {
    super(listenerContainer);
  }

 @Override
  public void onMessage(Message message, byte[] pattern) {
    String expirekey = message.toString();
    if (expirekey.contains(POST_ID_KEY)){
      Long size = stringRedisTemplate.opsForHyperLogLog().size(PREFIX + expirekey);
      stringRedisTemplate.delete(PREFIX + expirekey);
      String postId = expirekey.substring(POST_ID_KEY.length());
      postService.updatePostPageview(postId, size);
    }
  }
}
